import {
	defineStore
} from 'pinia';
import http from '../common/request'
import {
	getToken,
	setToken,
	removeToken,
	setClientId,
	getClientId,
	getUserInfo,
	setUserInfo,
} from '@/common/auth'
import APP_INFO from '@/config.js';
export default defineStore('userStore', {
	state: () => {
		return {
			userInfo: getUserInfo(),
			token: getToken(),
			ClientId: getClientId(),
			roles: [],
			permissions: []
		}
	},
	actions: {
		set_UserInfo(userInfo) {
			this.userInfo = userInfo;
		},
		SET_TOKEN(token) {
			this.token = token;
		},
		SET_ClientId(ClientId) {
			this.ClientId = ClientId
		},
		set_Roles(roles) {
			this.roles = roles
		},
		set_Permissions(permissions) {
			this.permissions = permissions
		},
		clear() {
			this.userInfo = {};
		},
		//登录
		handleLogin(loginForm) {
			return new Promise((resolve, reject) => {
				http({
					url: '/auth/login',
					method: 'POST',
					data: {
						username: loginForm.username,
						password: loginForm.password,
						code: loginForm.code,
						uuid: loginForm.uuid,
						grantType: "password",
						tenantId: APP_INFO.tenantId,
						clientId: "e5cd7e4891bf95d1d19206ce24a7b32e",
					}
				}).then(res => {
					let data = res?.data;
					this.SET_TOKEN(data?.access_token);
					this.SET_ClientId(data?.client_id);
					setToken(data?.access_token);
					setClientId(data?.client_id);
					this.handleUserInfo().then(userRes => {
						resolve();
					})

				}).catch(error => {
					reject(error)
				})
			})
		},
		handleUserInfo() {
			return new Promise((resolve, reject) => {
				http({
					url: '/system/user/getInfo',
					method: 'GET',
					data: {}
				}).then(res => {
					let data = res.data;
					this.set_UserInfo(data.user);
					setUserInfo(data.user);
					this.set_Roles(data.roles);
					this.set_Permissions(data.permissions);
					resolve();
				})
			});
		},
	}
})